package com.xia.user.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xia.handler.UserException;
import com.xia.response.Result;
import com.xia.response.ResultCode;
import com.xia.user.entity.User;
import com.xia.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xia
 * @since 2020-10-06
 * CrossOrigin 解决跨域问题
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户查询管理", tags = "系统用户模块")
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping
    @ApiOperation(value = "查询所有用户",notes = "查询用户列表")
    public Result getFindAllUser(){
        List<User> userList = userService.list();
        return Result.ok().data("users",userList);
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "查询单个用户信息",notes = "通过id 查询单个用户")
    public Result getUserById(@PathVariable("id") Long id){
        User user = userService.getById(id);
      if(user != null){
          return Result.ok().data("user",user);
      }else{
          throw new UserException(ResultCode.USER_NOT_EXCEPTION.getCode(),ResultCode.USER_NOT_EXCEPTION.getMessage());
      }
    }

    @GetMapping("/findUserList")
    @ApiOperation(value = "用户分页查询",notes = "用户分页查询")
    public Result findUserList(@RequestParam(required = true,defaultValue = "1") Integer current,
                               @RequestParam(required = true,defaultValue = "7") Integer size){
        Page<User> page = new Page<>(current,size);
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();

        return Result.ok().data("total",total).data("records",records);
    }

}

